<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd" v-if="hasPermission('system:role:add')">
            新增角色
          </el-button>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="searchForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 角色列表 -->
      <el-table :data="roleList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              @click="handleAssignPermissions(scope.row)" 
              v-if="hasPermission('system:role:update')"
            >
              分配权限
            </el-button>
            <el-button 
              size="small" 
              @click="handleEdit(scope.row)" 
              v-if="hasPermission('system:role:update')"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)" 
              v-if="hasPermission('system:role:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />

      <!-- 角色编辑对话框 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
        <el-form :model="currentRole" :rules="roleRules" ref="roleFormRef" label-width="80px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="currentRole.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色编码" prop="code">
            <el-input v-model="currentRole.code" placeholder="请输入角色编码" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input 
              v-model="currentRole.description" 
              type="textarea" 
              placeholder="请输入角色描述" 
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="currentRole.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveRole">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleList, addRole, updateRole, deleteRole } from '@/api/role'

const router = useRouter()

// 角色列表
const roleList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单引用
const roleFormRef = ref()

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleCode: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 当前编辑的角色
const currentRole = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ]
}

// 权限检查函数（模拟）
const hasPermission = (permission) => {
  // 在实际应用中，这里应该检查用户是否具有指定权限
  // 简化处理，假设当前用户是管理员
  return true
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const response = await getRoleList()
    if (response.code === 200) {
      roleList.value = response.data
      pagination.total = response.data.length
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (err) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.roleName = ''
  searchForm.roleCode = ''
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  isEdit.value = false
  // 重置表单
  Object.assign(currentRole, {
    id: '',
    name: '',
    code: '',
    description: '',
    status: 1
  })
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (role) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  // 填充表单数据
  Object.assign(currentRole, {
    id: role.id,
    name: role.name,
    code: role.code,
    description: role.description,
    status: role.status
  })
  dialogVisible.value = true
}

// 处理分配权限
const handleAssignPermissions = (role) => {
  router.push(`/role/${role.id}/permissions`)
}

// 保存角色
const saveRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (isEdit.value) {
          response = await updateRole(currentRole)
        } else {
          response = await addRole(currentRole)
        }
        
        if (response.code === 200) {
          ElMessage.success(`${isEdit.value ? '编辑' : '新增'}角色成功`)
          dialogVisible.value = false
          fetchRoleList()
        } else {
          ElMessage.error(response.message || `${isEdit.value ? '编辑' : '新增'}角色失败`)
        }
      } catch (err) {
        ElMessage.error(`${isEdit.value ? '编辑' : '新增'}角色失败`)
      }
    }
  })
}

// 处理删除
const handleDelete = (role) => {
  ElMessageBox.confirm(`确定要删除角色"${role.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteRole(role.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchRoleList()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (err) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchRoleList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRoleList()
}

// 页面加载时获取角色列表
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>